import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class ReliableHeaderList extends StatefulWidget {
  const ReliableHeaderList({super.key});

  @override
  State<ReliableHeaderList> createState() => _ReliableHeaderListState();
}

class _ReliableHeaderListState extends State<ReliableHeaderList> {
  // Header是否可见
  bool _isHeaderVisible = false;
  // Header高度
  final double _headerHeight = 120.0;
  // 最小下拉距离阈值（触发显示）
  final double _showThreshold = 40.0;
  // 最小上推距离阈值（触发隐藏）
  final double _hideThreshold = 30.0;
  // 记录滚动位置
  double _scrollOffset = 0.0;
  // 记录上一帧滚动位置
  double _prevScrollOffset = 0.0;
  // 滚动控制器
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    // 监听滚动事件
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  // 处理滚动事件
  void _onScroll() {
    setState(() {
      _scrollOffset = _scrollController.position.pixels;
      final delta = _scrollOffset - _prevScrollOffset;

      print('delta ==== ${delta}, _scrollOffset: ${_scrollOffset},, _prevScrollOffset: ${_prevScrollOffset}');
      // 情况1：向上滚动（下拉动作）
      if (delta < 0) {
        // 列表在顶部时，只要有向上滚动就显示Header
        if (_scrollOffset <= 0) {
          _isHeaderVisible = true;
        }
        // 列表不在顶部，向上滚动距离足够时显示
        else if (!_isHeaderVisible && delta < -_showThreshold) {
          _isHeaderVisible = true;
        }
      }
      // 情况2：向下滚动（上推动作）
      else if (delta > 0) {
        // 已显示Header，且向下滚动距离足够时隐藏
        /*if (_isHeaderVisible && delta > _hideThreshold) {
          _isHeaderVisible = false;
        }*/
        _isHeaderVisible = false;
      }

      _prevScrollOffset = _scrollOffset;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('可靠的下拉显示Header'),
      ),
      body: CustomScrollView(
        controller: _scrollController,
        // 始终允许滚动，即使在顶部
        physics: const BouncingScrollPhysics(
          parent: AlwaysScrollableScrollPhysics(),
        ),
        slivers: [
          // 动态Header
          SliverToBoxAdapter(
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 600),
              curve: Curves.easeInOut,
              height: _isHeaderVisible ? _headerHeight : 0,
              child: Container(
                color: Colors.tealAccent,
                padding: const EdgeInsets.all(20),
                alignment: Alignment.center,
                child: const Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      '下拉显示的Header',
                      style: TextStyle(
                        fontSize: 22,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                    SizedBox(height: 10),
                    Text(
                      '初始隐藏，下拉显示，上推隐藏',
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.black54,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),

          // 列表内容
          SliverList(
            delegate: SliverChildBuilderDelegate(
                  (context, index) {
                return Text('TTTTT测试室收拾收拾四 ${index}');
              },
              childCount: 2,
            ),
          ),
        ],
      ),
    );
  }
}